<template>
  <div class="duty-schedule-container">
    <VRow>
      <!-- 左侧：老师信息卡片 -->
      <VCol cols="12" md="3">
        <VCard class="teacher-cards-container" elevation="2">
          <VCardTitle class="d-flex align-center justify-space-between">
            <span class="d-flex align-center">
              <VIcon icon="mdi-account-group" class="mr-2" />
              值班老师
            </span>
            <div class="d-flex">
              <VBtn 
                icon="mdi-refresh" 
                size="small" 
                variant="text"
                @click="refreshAllData"
                :loading="saving"
                title="刷新数据"
                class="mr-1"
              />
              <VBtn 
                icon="mdi-account-check" 
                size="small" 
                variant="text"
                @click="manualCheck"
                :loading="isCheckingStatus"
                title="检查老师状态变化"
                color="primary"
              />
            </div>
          </VCardTitle>
          <VCardText>
            <!-- 状态指示器 -->
            <div class="status-indicator mb-3">
              <div class="d-flex align-center justify-space-between">
                <div class="d-flex align-center">
                  <VIcon 
                    :icon="isCheckingStatus ? 'mdi-loading' : 'mdi-check-circle'" 
                    :color="isCheckingStatus ? 'primary' : 'success'"
                    size="14"
                                         :class="{ rotating: isCheckingStatus }"
                    class="mr-1"
                  />
                  <span class="text-caption">
                    {{ isCheckingStatus ? '正在检查...' : '自动检查已启用' }}
                  </span>
                </div>
                <span v-if="lastCheckTime" class="text-caption text-grey">
                  {{ formatTime(lastCheckTime) }}
                </span>
              </div>
            </div>
            
            <!-- 初访员 -->
            <div class="teacher-section mb-4">
              <h4 class="text-subtitle-1 mb-2 d-flex align-center">
                <VIcon icon="mdi-account-search" size="16" class="mr-1" />
                初访员
              </h4>
              <div 
                v-for="teacher in initialVisitors" 
                :key="teacher.id"
                :class="[
                  'teacher-card',
                  { 'being-dragged': draggedTeacher?.id === teacher.id }
                ]"
                draggable="true"
                @dragstart="handleDragStart(teacher, $event)"
                @dragend="handleDragEnd"
              >
                <VAvatar size="32" class="mr-2">
                  <VImg 
                    v-if="teacher.avatar && teacher.avatar.startsWith('data:image')" 
                    :src="teacher.avatar"
                    alt="老师头像"
                  />
                  <VImg 
                    v-else 
                    src="/assets/images/avatars/avatar-1.png"
                    alt="默认头像"
                  />
                </VAvatar>
                <div class="teacher-info">
                  <div class="teacher-name">{{ teacher.name }}</div>
                  <div class="teacher-title">{{ teacher.title }}</div>
                </div>
                <VIcon icon="mdi-drag" size="16" class="drag-handle" />
              </div>
            </div>

            <!-- 咨询师 -->
            <div class="teacher-section">
              <h4 class="text-subtitle-1 mb-2 d-flex align-center">
                <VIcon icon="mdi-account-heart" size="16" class="mr-1" />
                咨询师
              </h4>
              <div 
                v-for="teacher in consultants" 
                :key="teacher.id"
                :class="[
                  'teacher-card',
                  { 'being-dragged': draggedTeacher?.id === teacher.id }
                ]"
                draggable="true"
                @dragstart="handleDragStart(teacher, $event)"
                @dragend="handleDragEnd"
              >
                <VAvatar size="32" class="mr-2">
                  <VImg 
                    v-if="teacher.avatar && teacher.avatar.startsWith('data:image')" 
                    :src="teacher.avatar"
                    alt="老师头像"
                  />
                  <VImg 
                    v-else 
                    src="/assets/images/avatars/avatar-1.png"
                    alt="默认头像"
                  />
                </VAvatar>
                <div class="teacher-info">
                  <div class="teacher-name">{{ teacher.name }}</div>
                  <div class="teacher-title">{{ teacher.title }}</div>
                </div>
                <VIcon icon="mdi-drag" size="16" class="drag-handle" />
              </div>
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <!-- 右侧：日历和值班安排 -->
      <VCol cols="12" md="9">
        <VCard elevation="2">
          <VCardTitle class="d-flex align-center justify-space-between">
            <span class="d-flex align-center">
              <VIcon icon="mdi-calendar-clock" class="mr-2" />
              值班安排
            </span>
            <div class="d-flex align-center">
              <VBtn icon="mdi-chevron-left" @click="previousMonth" variant="text" />
              <span class="mx-4 text-h6">{{ currentMonthYear }}</span>
              <VBtn icon="mdi-chevron-right" @click="nextMonth" variant="text" />
              <VBtn 
                color="primary" 
                @click="showScheduleDialog = true"
                prepend-icon="mdi-plus"
                class="ml-4"
              >
                添加值班
              </VBtn>
            </div>
          </VCardTitle>
          
          <VCardText>
            <div class="calendar-grid">
              <div class="calendar-header">
                <div v-for="day in weekDays" :key="day" class="day-header">
                  {{ day }}
                </div>
              </div>
              <div class="calendar-body">
                <div 
                  v-for="date in calendarDates" 
                  :key="date.key"
                  :class="[
                    'date-cell',
                    { 'other-month': !date.isCurrentMonth },
                    { 'today': date.isToday },
                    { 'has-duty': date.hasDuty },
                    { 'drop-zone': isDragOver && date.isCurrentMonth }
                  ]"
                  @click="openDayDetail(date)"
                  @drop="handleDrop(date, $event)"
                  @dragover="handleDragOver($event)"
                  @dragenter="handleDragEnter"
                  @dragleave="handleDragLeave"
                >
                  <div class="date-number">{{ date.day }}</div>
                  
                  <!-- 值班信息显示 -->
                  <div v-if="date.duties && date.duties.length > 0" class="duty-info">
                    <div 
                      v-for="duty in date.duties.slice(0, 2)" 
                      :key="duty.id"
                      :class="[
                        'duty-item',
                        duty.role === 'INITIAL_VISITOR' ? 'duty-initial' : 'duty-consultant'
                      ]"
                    >
                      <div class="duty-text">
                        {{ duty.teacherName }} {{ duty.timeSlot }}
                      </div>
                    </div>
                    <div v-if="date.duties.length > 2" class="duty-more">
                      +{{ date.duties.length - 2 }}
                    </div>
                  </div>
                  
                  <!-- 批量值班预览块 -->
                  <div 
                    v-if="batchPreview && isBatchPreviewOnDate(date)"
                    :class="[
                      'batch-preview-block',
                      batchPreview.role === 'INITIAL_VISITOR' ? 'batch-initial' : 'batch-consultant',
                      { 'is-start-date': isBatchStartDate(date) },
                      { 'is-end-date': isBatchEndDate(date) },
                      { 'is-middle-date': isBatchMiddleDate(date) }
                    ]"
                  >
                    <!-- 左边缘拖拽手柄 -->
                    <div 
                      v-if="isBatchStartDate(date)"
                      class="resize-handle resize-left"
                      @mousedown="startResize('left', $event)"
                      title="拖拽调整开始日期"
                    >
                      <VIcon icon="mdi-drag-horizontal" size="10" />
                    </div>
                    
                    <!-- 批量值班信息 -->
                    <div class="batch-info">
                      <div class="batch-teacher-name">{{ batchPreview.teacherName }}</div>
                      <div class="batch-time">{{ batchPreview.startTime }}-{{ batchPreview.endTime }}</div>
                      <div class="batch-date-range">
                        {{ formatDateToString(batchPreview.startDate) }} ~ {{ formatDateToString(batchPreview.endDate) }}
                      </div>
                    </div>
                    
                    <!-- 右边缘拖拽手柄 -->
                    <div 
                      v-if="isBatchEndDate(date)"
                      class="resize-handle resize-right"
                      @mousedown="startResize('right', $event)"
                      title="拖拽调整结束日期"
                    >
                      <VIcon icon="mdi-drag-horizontal" size="10" />
                    </div>
                  </div>
                  
                  <!-- 批量操作按钮 - 独立显示在日期格子上方 -->
                  <div 
                    v-if="batchPreview && isBatchStartDate(date)" 
                    class="batch-actions-overlay"
                  >
                    <VBtn 
                      icon="mdi-check" 
                      size="small" 
                      color="success" 
                      variant="elevated"
                      @click="confirmBatchPreview"
                      title="确认创建批量值班"
                      :loading="saving"
                    />
                    <VBtn 
                      icon="mdi-close" 
                      size="small" 
                      color="error" 
                      variant="elevated"
                      @click="cancelBatchPreview"
                      title="取消预览"
                      class="ml-1"
                    />
                  </div>
                </div>
              </div>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- 日期详情弹窗 -->
    <VDialog v-model="showDayDialog" max-width="1000px" max-height="80vh" @click:outside="closeDayDialog">
      <VCard v-if="selectedDate">
        <VCardTitle class="d-flex align-center justify-space-between">
          <span>{{ formatDate(selectedDate.date) }} 值班安排</span>
          <VBtn icon @click="closeDayDialog">
            <VIcon>mdi-close</VIcon>
          </VBtn>
        </VCardTitle>
        
        <VCardText>
          <div class="day-detail-container">
            <!-- 时间轴 -->
            <div class="time-slots">
              <div 
                v-for="hour in workingHours" 
                :key="hour"
                :class="[
                  'time-slot',
                  { 'has-duty': getHourDuties(hour).length > 0 }
                ]"
                @drop="handleTimeSlotDrop(hour, $event)"
                @dragover="handleDragOver($event)"
                @dragenter="handleDragEnter"
                @dragleave="handleDragLeave"
              >
                <div class="time-label">{{ hour }}:00</div>
                <div class="duty-assignments">
                  <div 
                    v-for="duty in getHourDuties(hour)" 
                    :key="duty.id"
                    :class="[
                      'duty-assignment',
                      duty.role === 'INITIAL_VISITOR' ? 'duty-initial' : 'duty-consultant'
                    ]"
                  >
                    <VAvatar size="24" class="mr-2">
                      <VImg 
                        v-if="duty.teacherAvatar && duty.teacherAvatar.startsWith('data:image')" 
                        :src="duty.teacherAvatar"
                        alt="老师头像"
                      />
                      <VImg 
                        v-else 
                        src="/assets/images/avatars/avatar-1.png"
                        alt="默认头像"
                      />
                    </VAvatar>
                    <div class="duty-details">
                      <div class="teacher-name">{{ duty.teacherName }}</div>
                      <div class="duty-time">{{ duty.startTime }} - {{ duty.endTime }}</div>
                      <div class="duty-location">{{ duty.location }}</div>
                    </div>
                    <VBtn 
                      icon 
                      size="small" 
                      color="error" 
                      variant="text"
                      @click="deleteDuty(duty.id)"
                    >
                      <VIcon size="16">mdi-delete</VIcon>
                    </VBtn>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </VCardText>
      </VCard>
    </VDialog>

    <!-- 添加值班弹窗 -->
    <VDialog v-model="showScheduleDialog" max-width="700px" max-height="70vh" @click:outside="closeScheduleDialog">
      <VCard>
        <VCardTitle>添加值班安排</VCardTitle>
        <VCardText>
          <VForm ref="scheduleFormRef" v-model="scheduleFormValid">
            <VRow>
              <VCol cols="12" sm="6">
                <VSelect
                  v-model="scheduleForm.teacherId"
                  :items="allTeachers"
                  item-title="name"
                  item-value="id"
                  label="选择老师 *"
                  :rules="[rules.required]"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VSelect
                  v-model="scheduleForm.role"
                  :items="roleOptions"
                  label="值班类型 *"
                  :rules="[rules.required]"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="scheduleForm.date"
                  type="date"
                  label="值班日期 *"
                  :rules="[rules.required]"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VSelect
                  v-model="scheduleForm.location"
                  :items="locationOptions"
                  label="值班地点"
                  placeholder="请选择值班地点"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="scheduleForm.startTime"
                  type="time"
                  label="开始时间 *"
                  :rules="[rules.required]"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="scheduleForm.endTime"
                  type="time"
                  label="结束时间 *"
                  :rules="[rules.required, rules.endTimeAfterStart]"
                  variant="outlined"
                />
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn color="secondary" @click="closeScheduleDialog">取消</VBtn>
          <VBtn 
            color="primary" 
            @click="saveSchedule"
            :loading="saving"
            :disabled="!scheduleFormValid"
          >
            保存
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- 删除确认对话框 -->
    <VDialog v-model="showDeleteDialog" max-width="500px" persistent @click:outside="cancelDeleteDuty">
      <VCard>
        <VCardTitle class="d-flex align-center">
          <VIcon icon="mdi-delete-alert" color="error" class="mr-2" />
          <span>确认删除值班安排</span>
        </VCardTitle>
        <VCardText>
          <VAlert 
            type="warning" 
            color="warning"
            variant="tonal"
            class="mb-4"
          >
            <VIcon icon="mdi-alert-circle" class="mr-2" />
            此操作不可恢复，请谨慎操作
          </VAlert>
          
          <div v-if="deletingDuty" class="deletion-details">
            <p><strong>确定要删除以下值班安排吗？</strong></p>
            <div class="duty-details mt-3">
              <div class="detail-item">
                <VIcon icon="mdi-account" size="16" class="mr-2" />
                <span>{{ deletingDuty.teacher_name || '未知老师' }}</span>
              </div>
              <div class="detail-item">
                <VIcon icon="mdi-calendar" size="16" class="mr-2" />
                <span>{{ formatDate(new Date(deletingDuty.start_time)) }}</span>
              </div>
              <div class="detail-item">
                <VIcon icon="mdi-clock" size="16" class="mr-2" />
                <span>{{ formatTimeSlot(deletingDuty.start_time, deletingDuty.end_time) }}</span>
              </div>
              <div class="detail-item">
                <VIcon icon="mdi-map-marker" size="16" class="mr-2" />
                <span>{{ deletingDuty.location || '未指定地点' }}</span>
              </div>
            </div>
          </div>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn color="secondary" variant="outlined" @click="cancelDeleteDuty">取消</VBtn>
          <VBtn color="error" @click="confirmDeleteDuty">确认删除</VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
    
    <!-- 批量时间设置对话框 -->
    <VDialog 
      v-model="showBatchTimeDialog" 
      max-width="500"
      persistent
      @click:outside="cancelBatchTimeDialog"
    >
      <VCard class="batch-time-dialog">
        <VCardTitle class="text-h6 pa-4 bg-primary text-white d-flex align-center">
          <VIcon icon="mdi-clock-outline" class="mr-2" />
          设置批量值班时间
        </VCardTitle>
        
        <VCardText class="pa-4">
          <VRow>
            <VCol cols="12" class="pb-2">
              <VAlert 
                type="info" 
                variant="tonal"
                class="mb-4"
              >
                <div class="text-subtitle-2">
                  <VIcon icon="mdi-account" size="small" class="mr-1" />
                  老师：{{ batchPreview?.teacherName }}
                </div>
                <div class="text-subtitle-2 mt-1">
                  <VIcon icon="mdi-calendar-range" size="small" class="mr-1" />
                  日期范围：{{ batchPreview ? formatDateToString(batchPreview.startDate) : '' }} ~ {{ batchPreview ? formatDateToString(batchPreview.endDate) : '' }}
                </div>
              </VAlert>
            </VCol>
            
            <VCol cols="6">
              <VTextField
                v-model="batchTimeForm.startTime"
                label="开始时间"
                type="time"
                variant="outlined"
                density="compact"
                prepend-inner-icon="mdi-clock-start"
                color="primary"
              />
            </VCol>
            
            <VCol cols="6">
              <VTextField
                v-model="batchTimeForm.endTime"
                label="结束时间"
                type="time"
                variant="outlined"
                density="compact"
                prepend-inner-icon="mdi-clock-end"
                color="primary"
              />
            </VCol>
            
            <VCol cols="12">
              <VSelect
                v-model="batchTimeForm.location"
                :items="locationOptions"
                label="值班地点"
                variant="outlined"
                density="compact"
                prepend-inner-icon="mdi-map-marker"
                placeholder="请选择值班地点"
                color="primary"
              />
            </VCol>
          </VRow>
        </VCardText>
        
        <VCardActions class="px-4 pb-4">
          <VSpacer />
          <VBtn
            color="grey-darken-1"
            variant="outlined"
            @click="cancelBatchTimeDialog"
            prepend-icon="mdi-close"
          >
            取消
          </VBtn>
          <VBtn
            color="primary"
            variant="elevated"
            @click="confirmBatchTime"
            prepend-icon="mdi-check"
            :loading="saving"
          >
            确认创建
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useSnackbarStore } from '@/store/snackbarStore';
import { fetchUserList } from '@/api/user';
import { fetchDutyList, addDuty, deleteDuty as removeDuty, batchAddDuty } from '@/api/duty';
import { getActiveWorkingHours, getActiveIntervals, generateWorkingHours } from '@/api/timeConfig';

// 类型定义
interface Teacher {
  id: number;
  name: string;
  role: string;
  title: string;
  avatar: string | null;
}

interface BatchPreview {
  teacherId: number;
  teacherName: string;
  role: string;
  startDate: Date;
  endDate: Date;
  startTime: string;
  endTime: string;
  location: string;
}

interface DateObj {
  key: number;
  day: number;
  date: Date;
  isCurrentMonth: boolean;
  isToday: boolean;
  hasDuty: boolean;
  duties: any[];
}

interface DutyForm {
  teacherId: number | null;
  role: string;
  date: string;
  startTime: string;
  endTime: string;
  location: string;
}

const snackbarStore = useSnackbarStore();

// 响应式数据
const currentDate = ref(new Date());
const selectedDate = ref<DateObj | null>(null);
const showDayDialog = ref(false);
const showScheduleDialog = ref(false);
const scheduleFormValid = ref(false);
const scheduleFormRef = ref();
const saving = ref(false);

// 拖拽相关
const draggedTeacher = ref<Teacher | null>(null);
const isDragOver = ref(false);

// 删除确认对话框
const showDeleteDialog = ref(false);
const deletingDuty = ref<any>(null);

// 批量值班预览相关
const batchPreview = ref<BatchPreview | null>(null);
const isResizing = ref(false);
const resizeDirection = ref<'left' | 'right' | null>(null);
const initialMouseX = ref(0);
const initialStartDate = ref<Date | null>(null);
const initialEndDate = ref<Date | null>(null);
const showBatchTimeDialog = ref(false);
const batchTimeForm = reactive({
  startTime: '09:00',
  endTime: '17:00',
  location: ''
});

// 动态检验状态
const isCheckingStatus = ref(false);
const lastCheckTime = ref<Date | null>(null);

// 老师数据
const initialVisitors = ref<Teacher[]>([]);
const consultants = ref<Teacher[]>([]);
const duties = ref<any[]>([]);

// 表单数据
const scheduleForm = reactive<DutyForm>({
  teacherId: null,
  role: '',
  date: '',
  startTime: '',
  endTime: '',
  location: ''
});

// 工作时间（从配置中动态获取）
const workingHours = ref<number[]>([8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]);
const timeConfigs = ref<any[]>([]);
const intervalConfigs = ref<any[]>([]);

// 选项数据
const roleOptions = [
  { title: '初访员', value: 'INITIAL_VISITOR' },
  { title: '咨询师', value: 'CONSULTANT' }
];

const locationOptions = [
  '心理咨询中心101室',
  '心理咨询中心102室',
  '心理咨询中心201室',
  '心理咨询中心202室'
];

const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 验证规则
const rules = {
  required: (v: any) => !!v || '此项为必填项',
  endTimeAfterStart: (v: string) => {
    if (!v || !scheduleForm.startTime) return true;
    return v > scheduleForm.startTime || '结束时间必须晚于开始时间';
  }
};

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    if (showScheduleDialog.value) {
      closeScheduleDialog();
    } else if (showDayDialog.value) {
      closeDayDialog();
    }
  }
};

// 计算属性
const currentMonthYear = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth() + 1;
  return `${year}年${month}月`;
});

const allTeachers = computed(() => {
  // 只包含启用的老师（initialVisitors 和 consultants 已经过滤过了）
  return [...initialVisitors.value, ...consultants.value];
});

const calendarDates = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  
  const startDate = new Date(firstDay);
  startDate.setDate(firstDay.getDate() - firstDay.getDay());
  
  const endDate = new Date(lastDay);
  endDate.setDate(lastDay.getDate() + (6 - lastDay.getDay()));
  
  const dates: DateObj[] = [];
  const currentDateValue = new Date(startDate);
  
  while (currentDateValue <= endDate) {
    const dateObj: DateObj = {
      key: currentDateValue.getTime(),
      day: currentDateValue.getDate(),
      date: new Date(currentDateValue),
      isCurrentMonth: currentDateValue.getMonth() === month,
      isToday: isToday(currentDateValue),
      hasDuty: hasDutyOnDate(currentDateValue),
      duties: getDutiesForDate(currentDateValue)
    };
    dates.push(dateObj);
    currentDateValue.setDate(currentDateValue.getDate() + 1);
  }
  
  return dates;
});

// 方法
const isToday = (date: Date) => {
  const today = new Date();
  return date.toDateString() === today.toDateString();
};

const hasDutyOnDate = (date: Date) => {
  return duties.value.some((duty: any) => {
    const dutyDate = new Date(duty.start_time);
    return dutyDate.toDateString() === date.toDateString();
  });
};

const getDutiesForDate = (date: Date) => {
  return duties.value.filter((duty: any) => {
    const dutyDate = new Date(duty.start_time);
    return dutyDate.toDateString() === date.toDateString();
  }).map((duty: any) => ({
    ...duty,
    teacherName: duty.teacher_name || '未知老师',
    teacherAvatar: duty.teacher_avatar || null,
    startTime: new Date(duty.start_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    endTime: new Date(duty.end_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    timeSlot: formatTimeSlot(duty.start_time, duty.end_time)
  }));
};

const getHourDuties = (hour: number) => {
  if (!selectedDate.value) return [];
  
  return duties.value.filter((duty: any) => {
    const dutyDate = new Date(duty.start_time);
    const endDate = new Date(duty.end_time);
    
    // 检查是否是选中的日期
    if (dutyDate.toDateString() !== selectedDate.value!.date.toDateString()) {
      return false;
    }
    
    // 检查时间是否在当前小时内
    const dutyStartHour = dutyDate.getHours();
    const dutyEndHour = endDate.getHours();
    
    return hour >= dutyStartHour && hour < dutyEndHour;
  }).map((duty: any) => ({
    ...duty,
    teacherName: duty.teacher_name || '未知老师',
    teacherAvatar: duty.teacher_avatar || null,
    startTime: new Date(duty.start_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    endTime: new Date(duty.end_time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    location: duty.location || '未指定地点'
  }));
};

// 格式化日期为 YYYY-MM-DD 格式，避免时区问题
const formatDateToString = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  });
};

const formatTimeSlot = (startTime: string, endTime: string) => {
  const start = new Date(startTime);
  const end = new Date(endTime);
  return `${start.getHours()}:${start.getMinutes().toString().padStart(2, '0')}-${end.getHours()}:${end.getMinutes().toString().padStart(2, '0')}`;
};

const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
};

// 拖拽处理
const handleDragStart = (teacher: Teacher, event: DragEvent) => {
  draggedTeacher.value = teacher;
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('text/plain', JSON.stringify(teacher));
  }
};

const handleDragEnd = () => {
  draggedTeacher.value = null;
  isDragOver.value = false;
};

const handleDragOver = (event: DragEvent) => {
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move';
  }
};

const handleDragEnter = () => {
  isDragOver.value = true;
};

const handleDragLeave = () => {
  isDragOver.value = false;
};

const handleDrop = (dateObj: DateObj, event: DragEvent) => {
  event.preventDefault();
  isDragOver.value = false;
  
  if (!draggedTeacher.value || !dateObj.isCurrentMonth) return;
  
  // 创建批量值班预览
  const teacher = draggedTeacher.value;
  batchPreview.value = {
    teacherId: teacher.id,
    teacherName: teacher.name,
    role: teacher.role,
    startDate: new Date(dateObj.date),
    endDate: new Date(dateObj.date),
    startTime: '09:00',
    endTime: '17:00',
    location: teacher.role === 'INITIAL_VISITOR' ? '心理咨询中心101室' : '心理咨询中心201室'
  };
  
  // 初始化时间表单
  batchTimeForm.startTime = '09:00';
  batchTimeForm.endTime = '17:00';
  batchTimeForm.location = teacher.role === 'INITIAL_VISITOR' ? '心理咨询中心101室' : '心理咨询中心201室';
  
  // 显示时间选择对话框
  showBatchTimeDialog.value = true;
  
  // 调试信息
  console.log('批量预览创建成功:', batchPreview.value);
  
  draggedTeacher.value = null;
};

const handleTimeSlotDrop = (hour: number, event: DragEvent) => {
  event.preventDefault();
  
  if (!draggedTeacher.value || !selectedDate.value) return;
  
  // 预填充表单数据
  const teacher = draggedTeacher.value;
  const date = selectedDate.value.date;
  const formattedDate = formatDateToString(date);
  
  scheduleForm.teacherId = teacher.id;
  scheduleForm.role = teacher.role;
  scheduleForm.date = formattedDate;
  scheduleForm.startTime = `${hour.toString().padStart(2, '0')}:00`;
  scheduleForm.endTime = `${(hour + 2).toString().padStart(2, '0')}:00`; // 默认2小时
  scheduleForm.location = teacher.role === 'INITIAL_VISITOR' ? '心理咨询中心101室' : '心理咨询中心201室';
  
  // 关闭日期详情对话框，打开添加值班对话框
  showDayDialog.value = false;
  showScheduleDialog.value = true;
  
  // 显示成功提示
  snackbarStore.showMessage(`已为 ${teacher.name} 预填充 ${formattedDate} ${hour}:00 时段的值班信息，请确认后保存`, 'success');
  
  draggedTeacher.value = null;
};

// 日历操作
const previousMonth = () => {
  const newDate = new Date(currentDate.value);
  newDate.setMonth(newDate.getMonth() - 1);
  currentDate.value = newDate;
};

const nextMonth = () => {
  const newDate = new Date(currentDate.value);
  newDate.setMonth(newDate.getMonth() + 1);
  currentDate.value = newDate;
};

const openDayDetail = (dateObj: DateObj) => {
  if (!dateObj.isCurrentMonth) return;
  selectedDate.value = dateObj;
  showDayDialog.value = true;
};

const closeDayDialog = () => {
  showDayDialog.value = false;
  selectedDate.value = null;
};

// 表单操作
const closeScheduleDialog = () => {
  showScheduleDialog.value = false;
  resetScheduleForm();
};

const resetScheduleForm = () => {
  scheduleForm.teacherId = null;
  scheduleForm.role = '';
  scheduleForm.date = '';
  scheduleForm.startTime = '';
  scheduleForm.endTime = '';
  scheduleForm.location = '';
};

const saveSchedule = async () => {
  if (!scheduleFormRef.value?.validate() && showScheduleDialog.value) return;
  
  if (!scheduleForm.teacherId) {
    snackbarStore.showMessage('请选择老师', 'error');
    return;
  }
  
  saving.value = true;
  try {
    const dutyData = {
      user_id: scheduleForm.teacherId as number,
      role: scheduleForm.role,
      start_time: `${scheduleForm.date} ${scheduleForm.startTime}:00`,
      end_time: `${scheduleForm.date} ${scheduleForm.endTime}:00`,
      location: scheduleForm.location
    };
    
    const response = await addDuty(dutyData);
    if (response.data && (response.data.success || response.data.code === 200)) {
      snackbarStore.showMessage('值班安排添加成功', 'success');
      await loadDuties();
      closeScheduleDialog();
    } else {
      snackbarStore.showMessage('添加值班安排失败：' + (response.data?.message || '未知错误'), 'error');
    }
  } catch (error) {
    console.error('添加值班安排失败:', error);
    snackbarStore.showMessage('添加值班安排失败，请重试', 'error');
  } finally {
    saving.value = false;
  }
};

const deleteDuty = async (dutyId: number) => {
  // 找到要删除的值班信息
  const dutyToDelete = duties.value.find(duty => duty.id === dutyId);
  if (!dutyToDelete) return;
  
  deletingDuty.value = dutyToDelete;
  showDeleteDialog.value = true;
};

const confirmDeleteDuty = async () => {
  if (!deletingDuty.value) return;
  
  try {
    const response = await removeDuty(deletingDuty.value.id);
    if (response.data && (response.data.success || response.data.code === 200)) {
      snackbarStore.showMessage('值班安排删除成功', 'success');
      await loadDuties();
      showDeleteDialog.value = false;
      deletingDuty.value = null;
    } else {
      snackbarStore.showMessage('删除值班安排失败：' + (response.data?.message || '未知错误'), 'error');
    }
  } catch (error) {
    console.error('删除值班安排失败:', error);
    snackbarStore.showMessage('删除值班安排失败，请重试', 'error');
  }
};

const cancelDeleteDuty = () => {
  showDeleteDialog.value = false;
  deletingDuty.value = null;
};

// 数据加载
const loadTeachers = async () => {
  try {
    const response = await fetchUserList();
    if (response.data && response.data.success) {
      const teachers = response.data.data || [];
      
      // 过滤出启用的初访员
      initialVisitors.value = teachers
        .filter((teacher: any) => teacher.role === 'INITIAL_VISITOR' && teacher.is_active === true)
        .map((teacher: any) => {
          // 正确解析 extra_info
          const extraInfo = typeof teacher.extra_info === 'string' 
            ? JSON.parse(teacher.extra_info) 
            : teacher.extra_info || {};
          
          return {
            id: teacher.id,
            name: teacher.name,
            role: teacher.role,
            title: extraInfo.title || '初访员',
            avatar: extraInfo.avatar || null
          };
        });
        
      // 过滤出启用的咨询师
      consultants.value = teachers
        .filter((teacher: any) => teacher.role === 'CONSULTANT' && teacher.is_active === true)
        .map((teacher: any) => {
          // 正确解析 extra_info
          const extraInfo = typeof teacher.extra_info === 'string' 
            ? JSON.parse(teacher.extra_info) 
            : teacher.extra_info || {};
          
          return {
            id: teacher.id,
            name: teacher.name,
            role: teacher.role,
            title: extraInfo.title || '咨询师',
            avatar: extraInfo.avatar || null
          };
        });
        
      // 检查并清理被停用老师的值班记录
      await checkAndCleanInactiveTeacherDuties(teachers);
    }
  } catch (error) {
    console.error('加载老师数据失败:', error);
    snackbarStore.showMessage('加载老师数据失败', 'error');
  }
};

const loadDuties = async () => {
  try {
    const response = await fetchDutyList();
    if (response.data && (response.data.success || response.data.code === 200)) {
      duties.value = response.data.data || [];
    }
  } catch (error) {
    console.error('加载值班数据失败:', error);
    snackbarStore.showMessage('加载值班数据失败', 'error');
  }
};

// 检查并清理被停用老师的值班记录
const checkAndCleanInactiveTeacherDuties = async (allTeachers: any[]) => {
  try {
    // 获取所有被停用的老师ID
    const inactiveTeacherIds = allTeachers
      .filter((teacher: any) => teacher.is_active === false && (teacher.role === 'INITIAL_VISITOR' || teacher.role === 'CONSULTANT'))
      .map((teacher: any) => teacher.id);
    
    if (inactiveTeacherIds.length === 0) {
      return; // 没有被停用的老师，无需清理
    }
    
    // 获取当前所有值班记录
    const currentDuties = duties.value || [];
    
    // 找出被停用老师的值班记录
    const inactiveTeacherDuties = currentDuties.filter((duty: any) => 
      inactiveTeacherIds.includes(duty.user_id)
    );
    
    if (inactiveTeacherDuties.length === 0) {
      return; // 没有需要清理的值班记录
    }
    
    // 批量删除被停用老师的值班记录
    const deletePromises = inactiveTeacherDuties.map(async (duty: any) => {
      try {
        await removeDuty(duty.id);
        return { success: true, dutyId: duty.id, teacherName: duty.teacher_name };
      } catch (error) {
        console.error(`删除值班记录失败 (ID: ${duty.id}):`, error);
        return { success: false, dutyId: duty.id, teacherName: duty.teacher_name };
      }
    });
    
    const results = await Promise.all(deletePromises);
    const successCount = results.filter(r => r.success).length;
    const failCount = results.filter(r => !r.success).length;
    
    if (successCount > 0) {
      // 重新加载值班数据以更新界面
      await loadDuties();
      
      // 显示清理结果
      if (failCount === 0) {
        snackbarStore.showMessage(`已自动清理 ${successCount} 条被停用老师的值班记录`, 'success');
      } else {
        snackbarStore.showMessage(`已清理 ${successCount} 条值班记录，${failCount} 条清理失败`, 'warning');
      }
    }
  } catch (error) {
    console.error('清理被停用老师值班记录失败:', error);
    snackbarStore.showMessage('清理被停用老师值班记录失败', 'error');
  }
};

// 加载时间配置
const loadTimeConfigs = async () => {
  try {
    const workingHoursResponse = await getActiveWorkingHours();
    const intervalResponse = await getActiveIntervals();
    
    if (workingHoursResponse.success) {
      timeConfigs.value = workingHoursResponse.data;
      
      // 根据配置生成工作时间数组
      const allHours = new Set<number>();
      for (const config of workingHoursResponse.data) {
        if (config.startTime && config.endTime) {
          const hours = generateWorkingHours(config.startTime, config.endTime);
          hours.forEach(hour => allHours.add(hour));
        }
      }
      
      // 如果有配置，使用配置的时间；否则使用默认时间
      if (allHours.size > 0) {
        workingHours.value = Array.from(allHours).sort((a, b) => a - b);
      }
    }
    
    if (intervalResponse.success) {
      intervalConfigs.value = intervalResponse.data;
    }
  } catch (error) {
    console.error('加载时间配置失败：', error);
    snackbarStore.showMessage('加载时间配置失败', 'error');
  }
};

// 刷新所有数据的函数
const refreshAllData = async () => {
  await loadTimeConfigs();
  await loadTeachers(); // 这会自动清理被停用老师的值班记录
  await loadDuties();
};

// 定时检查被停用老师的值班记录
let checkInterval: NodeJS.Timeout | null = null;

// 启动动态检验
const startDynamicCheck = () => {
  // 清除之前的定时器
  if (checkInterval) {
    clearInterval(checkInterval);
  }
  
  // 每30秒检查一次
  checkInterval = setInterval(async () => {
    try {
      isCheckingStatus.value = true;
      
      // 获取最新的用户数据
      const response = await fetchUserList();
      if (response.data && response.data.success) {
        const allTeachers = response.data.data || [];
        
        // 检查是否有老师状态发生变化
        const currentActiveTeacherIds = new Set([
          ...initialVisitors.value.map(t => t.id),
          ...consultants.value.map(t => t.id)
        ]);
        
        const latestActiveTeacherIds = new Set(
          allTeachers
            .filter((teacher: any) => 
              teacher.is_active === true && 
              (teacher.role === 'INITIAL_VISITOR' || teacher.role === 'CONSULTANT')
            )
            .map((teacher: any) => teacher.id)
        );
        
        // 检查是否有老师被停用
        const hasInactiveTeachers = Array.from(currentActiveTeacherIds).some(id => 
          !latestActiveTeacherIds.has(id)
        );
        
        // 检查是否有新的活跃老师
        const hasNewActiveTeachers = Array.from(latestActiveTeacherIds).some(id => 
          !currentActiveTeacherIds.has(id)
        );
        
        // 如果有变化，重新加载数据
        if (hasInactiveTeachers || hasNewActiveTeachers) {
          console.log('检测到老师状态变化，正在更新数据...');
          await loadTeachers(); // 这会自动清理被停用老师的值班记录
          await loadDuties();
          snackbarStore.showMessage('检测到老师状态变化，已自动更新数据', 'info');
        }
      }
      
      lastCheckTime.value = new Date();
    } catch (error) {
      console.error('动态检验失败:', error);
    } finally {
      isCheckingStatus.value = false;
    }
  }, 30000); // 30秒检查一次
};

// 停止动态检验
const stopDynamicCheck = () => {
  if (checkInterval) {
    clearInterval(checkInterval);
    checkInterval = null;
  }
};

// 手动触发检验
const manualCheck = async () => {
  try {
    isCheckingStatus.value = true;
    snackbarStore.showMessage('正在检查老师状态变化...', 'info');
    
    // 获取最新的用户数据
    const response = await fetchUserList();
    if (response.data && response.data.success) {
      const allTeachers = response.data.data || [];
      
      // 检查并清理被停用老师的值班记录
      await checkAndCleanInactiveTeacherDuties(allTeachers);
      
      // 重新加载老师数据
      await loadTeachers();
      await loadDuties();
      
      lastCheckTime.value = new Date();
      snackbarStore.showMessage('检查完成，数据已更新', 'success');
    }
  } catch (error) {
    console.error('手动检验失败:', error);
    snackbarStore.showMessage('检查失败，请重试', 'error');
  } finally {
    isCheckingStatus.value = false;
  }
};

// 批量预览相关方法
const isBatchPreviewOnDate = (date: DateObj): boolean => {
  if (!batchPreview.value || !date.isCurrentMonth) return false;
  
  const dateStr = formatDateToString(date.date);
  const startStr = formatDateToString(batchPreview.value.startDate);
  const endStr = formatDateToString(batchPreview.value.endDate);
  
  return dateStr >= startStr && dateStr <= endStr;
};

const isBatchStartDate = (date: DateObj): boolean => {
  if (!batchPreview.value) return false;
  return formatDateToString(date.date) === formatDateToString(batchPreview.value.startDate);
};

const isBatchEndDate = (date: DateObj): boolean => {
  if (!batchPreview.value) return false;
  return formatDateToString(date.date) === formatDateToString(batchPreview.value.endDate);
};

const isBatchMiddleDate = (date: DateObj): boolean => {
  if (!batchPreview.value) return false;
  const dateStr = formatDateToString(date.date);
  const startStr = formatDateToString(batchPreview.value.startDate);
  const endStr = formatDateToString(batchPreview.value.endDate);
  return dateStr > startStr && dateStr < endStr;
};

// 调整大小处理
const startResize = (direction: 'left' | 'right', event: MouseEvent) => {
  if (!batchPreview.value) return;
  
  event.preventDefault();
  event.stopPropagation();
  
  isResizing.value = true;
  resizeDirection.value = direction;
  initialMouseX.value = event.clientX;
  initialStartDate.value = new Date(batchPreview.value.startDate);
  initialEndDate.value = new Date(batchPreview.value.endDate);
  
  document.addEventListener('mousemove', handleResize);
  document.addEventListener('mouseup', stopResize);
};

const handleResize = (event: MouseEvent) => {
  if (!isResizing.value || !batchPreview.value) return;
  
  const deltaX = event.clientX - initialMouseX.value;
  const cellWidth = 100; // 估算每个日期格子的宽度
  const daysDelta = Math.round(deltaX / cellWidth);
  
  if (resizeDirection.value === 'left') {
    const newStartDate = new Date(initialStartDate.value!);
    newStartDate.setDate(newStartDate.getDate() + daysDelta);
    
    if (newStartDate <= batchPreview.value.endDate) {
      batchPreview.value.startDate = newStartDate;
    }
  } else if (resizeDirection.value === 'right') {
    const newEndDate = new Date(initialEndDate.value!);
    newEndDate.setDate(newEndDate.getDate() + daysDelta);
    
    if (newEndDate >= batchPreview.value.startDate) {
      batchPreview.value.endDate = newEndDate;
    }
  }
};

const stopResize = () => {
  isResizing.value = false;
  resizeDirection.value = null;
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
};

// 确认批量预览
const confirmBatchPreview = async () => {
  if (!batchPreview.value) return;
  
  saving.value = true;
  
  try {
    const dutiesData: Array<{
      user_id: number;
      role: string;
      start_time: string;
      end_time: string;
      location: string;
    }> = [];
    const currentDate = new Date(batchPreview.value.startDate);
    const endDate = new Date(batchPreview.value.endDate);
    
    while (currentDate <= endDate) {
      const dateStr = formatDateToString(currentDate);
      
      dutiesData.push({
        user_id: batchPreview.value.teacherId,
        role: batchPreview.value.role,
        start_time: `${dateStr} ${batchPreview.value.startTime}:00`,
        end_time: `${dateStr} ${batchPreview.value.endTime}:00`,
        location: batchPreview.value.location
      });
      
      currentDate.setDate(currentDate.getDate() + 1);
    }
    
    console.log('准备发送到后端的数据:', dutiesData);
    const response = await batchAddDuty(dutiesData);
    console.log('后端返回的响应:', response.data);
    if (response.data && response.data.success) {
      snackbarStore.showMessage(`成功创建 ${dutiesData.length} 天的值班安排`, 'success');
      await loadDuties();
      cancelBatchPreview();
    } else {
      snackbarStore.showMessage('批量创建值班安排失败：' + (response.data?.message || '未知错误'), 'error');
      console.error('批量创建失败，后端返回:', response.data);
    }
  } catch (error) {
    console.error('批量创建值班安排失败:', error);
    snackbarStore.showMessage('批量创建值班安排失败，请重试', 'error');
  } finally {
    saving.value = false;
  }
};

const cancelBatchPreview = () => {
  batchPreview.value = null;
  snackbarStore.showMessage('已取消批量值班预览', 'info');
};

// 批量时间设置相关方法
const cancelBatchTimeDialog = () => {
  showBatchTimeDialog.value = false;
  batchPreview.value = null;
  snackbarStore.showMessage('已取消批量值班设置', 'info');
};

const confirmBatchTime = () => {
  if (!batchPreview.value) return;
  
  // 更新预览块的时间和地点
  batchPreview.value.startTime = batchTimeForm.startTime;
  batchPreview.value.endTime = batchTimeForm.endTime;
  batchPreview.value.location = batchTimeForm.location || 
    (batchPreview.value.role === 'INITIAL_VISITOR' ? '心理咨询中心101室' : '心理咨询中心201室');
  
  // 关闭对话框，显示预览块
  showBatchTimeDialog.value = false;
  snackbarStore.showMessage('时间设置完成，拖拽边缘可调整日期范围，点击确认按钮创建', 'success');
};

// 组件挂载和卸载
onMounted(() => {
  refreshAllData();
  
  // 启动动态检验
  startDynamicCheck();
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown);
  
  // 添加页面可见性监听，当页面重新获得焦点时刷新数据
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) {
      refreshAllData();
      // 重新启动动态检验
      startDynamicCheck();
    } else {
      // 页面隐藏时停止检验以节省资源
      stopDynamicCheck();
    }
  });
});

onUnmounted(() => {
  // 停止动态检验
  stopDynamicCheck();
  
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown);
  
  // 移除页面可见性监听
  document.removeEventListener('visibilitychange', () => {
    if (!document.hidden) {
      refreshAllData();
      startDynamicCheck();
    } else {
      stopDynamicCheck();
    }
  });
});
</script>

<style scoped>
.duty-schedule-container {
  padding: 20px;
}

.teacher-cards-container {
  height: fit-content;
  position: sticky;
  top: 20px;
}

.teacher-section {
  margin-bottom: 16px;
}

.teacher-card {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  cursor: grab;
  transition: all 0.2s;
}

.teacher-card:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transform: translateY(-1px);
}

.teacher-card.being-dragged {
  opacity: 0.5;
  transform: rotate(5deg);
}

.teacher-card:active {
  cursor: grabbing;
}

.teacher-info {
  flex: 1;
}

.teacher-name {
  font-weight: 600;
  color: #333;
}

.teacher-title {
  font-size: 12px;
  color: #666;
}

.drag-handle {
  color: #999;
}

.calendar-grid {
  width: 100%;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #f5f5f5;
  border-radius: 4px 4px 0 0;
}

.day-header {
  background-color: #e0e0e0;
  padding: 12px;
  text-align: center;
  font-weight: 600;
  font-size: 14px;
}

.calendar-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #f5f5f5;
}

.date-cell {
  background-color: white;
  min-height: 100px;
  padding: 8px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
}

.date-cell:hover {
  background-color: #f8f9fa;
}

.date-cell.other-month {
  background-color: #fafafa;
  color: #ccc;
}

.date-cell.today {
  background-color: #e3f2fd;
}

.date-cell.has-duty {
  border-left: 4px solid #2196f3;
}

.date-cell.drop-zone {
  background-color: #e8f5e8;
  border: 2px dashed #4caf50;
}

.date-number {
  font-weight: 600;
  margin-bottom: 4px;
}

.duty-info {
  font-size: 11px;
}

.duty-item {
  padding: 2px 4px;
  margin-bottom: 2px;
  border-radius: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.duty-initial {
  background-color: #fff3e0;
  color: #e65100;
}

.duty-consultant {
  background-color: #e8f5e8;
  color: #2e7d32;
}

.duty-more {
  color: #666;
  font-style: italic;
}

.day-detail-container {
  max-height: 60vh;
  overflow-y: auto;
  padding: 8px;
}

.time-slots {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-slot {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  min-height: 80px;
  transition: all 0.2s;
  margin-bottom: 4px;
}

.time-slot:hover {
  background-color: #f8f9fa;
}

.time-slot.has-duty {
  border-left: 4px solid #2196f3;
}

.time-label {
  width: 100px;
  font-weight: 600;
  color: #666;
  font-size: 16px;
  text-align: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 8px 12px;
  margin-right: 16px;
}

.duty-assignments {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.duty-assignment {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  background: white;
}

.duty-assignment.duty-initial {
  border-left: 4px solid #ff9800;
}

.duty-assignment.duty-consultant {
  border-left: 4px solid #4caf50;
}

.duty-details {
  flex: 1;
}

/* 批量预览块样式 */
.batch-preview-block {
  position: absolute;
  top: 20px;
  left: 1px;
  right: 1px;
  bottom: 1px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 20;
  overflow: visible;
  backdrop-filter: blur(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.batch-preview-block:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.batch-preview-block.batch-initial {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 50%, #90caf9 100%);
  border-image: linear-gradient(135deg, #2196f3, #1976d2) 1;
  border-style: solid;
  border-width: 2px;
}

.batch-preview-block.batch-consultant {
  background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 50%, #ce93d8 100%);
  border-image: linear-gradient(135deg, #9c27b0, #7b1fa2) 1;
  border-style: solid;
  border-width: 2px;
}

.batch-preview-block.is-start-date {
  border-radius: 4px 0 0 4px;
}

.batch-preview-block.is-end-date {
  border-radius: 0 4px 4px 0;
}

.batch-preview-block.is-middle-date {
  border-radius: 0;
  border-left: none;
  border-right: none;
}

.batch-info {
  flex: 1;
  text-align: center;
  padding: 4px 6px;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(2px);
}

.batch-teacher-name {
  font-size: 12px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1.3;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

.batch-time {
  font-size: 10px;
  color: #2c2c2c;
  line-height: 1.2;
  font-weight: 500;
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.6);
}

.resize-handle {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 12px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.1));
  cursor: ew-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(2px);
}

.resize-handle:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.4));
  border-color: rgba(255, 255, 255, 0.6);
  transform: scaleY(1.05);
}

.resize-left {
  left: 0;
  border-radius: 6px 0 0 6px;
}

.resize-right {
  right: 0;
  border-radius: 0 6px 6px 0;
}

.resize-handle .v-icon {
  color: rgba(0, 0, 0, 0.6);
  filter: drop-shadow(0 1px 1px rgba(255, 255, 255, 0.8));
}

.batch-actions-overlay {
  position: absolute;
  top: -45px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  z-index: 1000;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.98), rgba(248, 250, 252, 0.95));
  border-radius: 12px;
  padding: 6px 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25), 0 4px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(8px);
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.batch-actions-overlay .v-btn {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.2s ease;
}

.batch-actions-overlay .v-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.batch-date-range {
  font-size: 9px;
  color: #999;
  line-height: 1;
  margin-top: 1px;
}

/* 批量时间对话框样式 */
.batch-time-dialog {
  overflow: hidden;
}

.batch-time-dialog .v-card-title {
  background: linear-gradient(135deg, #1976d2, #42a5f5);
  color: white;
}

.batch-time-dialog .v-text-field .v-field {
  border-radius: 8px;
}

.batch-time-dialog .v-text-field--focused .v-field {
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.duty-details .teacher-name {
  font-weight: 600;
  color: #333;
}

.duty-time {
  font-size: 12px;
  color: #666;
}

.duty-location {
  font-size: 11px;
  color: #999;
}

/* 删除确认对话框样式 */
.deletion-details {
  padding: 8px;
}

.duty-details {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e0e0e0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #555;
}

.detail-item:last-child {
  margin-bottom: 0;
}

/* 状态指示器样式 */
.status-indicator {
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 8px;
}

/* 旋转动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.rotating {
  animation: spin 1s linear infinite;
}
</style> 